package com.sxhnpg.web.action;

import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.sxhnpg.constant.Constants;
import com.sxhnpg.exception.SxhnpgException;
import com.sxhnpg.manager.UserManager;
import com.sxhnpg.model.User;
import com.sxhnpg.util.DigestUtil;


public class LoginAction extends BaseAction{

	private String userid;
	private String password;

	private UserManager userManager;
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	private static Logger logger = Logger.getLogger(LoginAction.class);  
	
	public String login() throws SxhnpgException{
		Map<String, Object> session=(Map<String, Object>)ActionContext.getContext().getSession();
		try{
			String pwd = DigestUtil.md5Digest(password);
			User user=userManager.find(userid);
			if(user!=null && user.getPassword().equals(pwd)){
				// 更新登录时间
				user.setLastLoginTime(new Date());
				userManager.update(user);
				
				session.put(Constants.LOGIN_USER_INFO, user);
				
				return "success_login";
			}
			else{
				ServletActionContext.getRequest().setAttribute(Constants.LOGIN_ERROR_INFO, "账号或密码错误，或者该用户没有登录权限");
			return "fail_login";
			}
		}catch (Exception e) {
			logger.error("用户登录出错",e);
			throw new SxhnpgException();
		}
	}
	
	public String loginout() throws SxhnpgException{
		Map<String, Object> session=(Map<String, Object>)ActionContext.getContext().getSession();
		try{
			User user = (User)session.get("login_user");
			if( user != null ){
				session.put(Constants.LOGIN_USER_INFO,"");
				session.remove(Constants.LOGIN_USER_INFO);
				ServletActionContext.getRequest().setAttribute(Constants.LOGIN_SUCCUSS_INFO, "已安全退出");
			}
			else{
				ServletActionContext.getRequest().setAttribute(Constants.LOGIN_ERROR_INFO, "您没有登录");
			}
			return "loginout";
		}catch (Exception e) {
			logger.error("注销出错",e);
			throw new SxhnpgException();
		}
	}
	

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
}
